/**
 * 积分历史页面组件
 * 展示用户的积分获取和使用记录，包括时间、类型、数量等详细信息
 */
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useState, useEffect } from 'react'
import { useAppContext } from '../../store'
import { pointsUtils } from '../../utils/pointsUtils'
import { formatDateTime } from '../../utils'
import './history.scss'

/**
 * 积分历史页面组件
 * 提供积分记录展示、筛选、统计等功能
 */
export default function PointsHistory() {
  const { state } = useAppContext()
  
  // 积分历史记录列表
  const [history, setHistory] = useState<any[]>([])
  // 加载状态
  const [loading, setLoading] = useState(true)
  // 当前筛选类型
  const [filterType, setFilterType] = useState<string>('all')
  // 统计信息
  const [stats, setStats] = useState<any>({
    totalEarned: 0,
    totalUsed: 0,
    totalExpired: 0
  })

  /**
   * 组件挂载时加载积分历史
   */
  useEffect(() => {
    if (state.currentUser) {
      loadPointsHistory()
    }
  }, [state.currentUser])

  /**
   * 加载积分历史数据
   */
  const loadPointsHistory = async () => {
    if (!state.currentUser) return
    
    try {
      setLoading(true)
      
      // 获取用户积分历史记录
      const historyData = await pointsUtils.getUserTransactions(state.currentUser.id)
      setHistory(historyData)
      
      // 计算统计信息
      calculateStats(historyData)
      
    } catch (error) {
      console.error('加载积分历史失败:', error)
      Taro.showToast({
        title: '加载失败',
        icon: 'error'
      })
    } finally {
      setLoading(false)
    }
  }

  /**
   * 计算积分统计信息
   * @param historyData 历史记录数据
   */
  const calculateStats = (historyData: any[]) => {
    const statsData = {
      totalEarned: 0,
      totalUsed: 0,
      totalExpired: 0
    }
    
    historyData.forEach(record => {
      if (record.points > 0) {
        statsData.totalEarned += record.points
      } else {
        statsData.totalUsed += Math.abs(record.points)
      }
      
      if (record.isExpired) {
        statsData.totalExpired += Math.abs(record.points)
      }
    })
    
    setStats(statsData)
  }

  /**
   * 获取积分类型的中文显示文本
   * @param type 积分类型
   * @returns string 类型中文文本
   */
  const getTypeText = (type: string) => {
    const typeMap: Record<string, string> = {
      registration: '注册奖励',
      order: '订单奖励',
      rating: '评价奖励',
      share: '分享奖励',
      daily_login: '每日登录',
      consecutive_order: '连续下单',
      order_payment: '订单抵扣',
      points_expired: '积分过期',
      admin_adjustment: '管理员调整'
    }
    return typeMap[type] || type
  }

  /**
   * 获取积分类型的图标
   * @param type 积分类型
   * @returns string 图标文本
   */
  const getTypeIcon = (type: string) => {
    const iconMap: Record<string, string> = {
      registration: '🎁',
      order: '🛒',
      rating: '⭐',
      share: '📤',
      daily_login: '📅',
      consecutive_order: '🔥',
      order_payment: '💳',
      points_expired: '⏰',
      admin_adjustment: '⚙️'
    }
    return iconMap[type] || '💰'
  }

  /**
   * 处理筛选类型变化
   * @param type 筛选类型
   */
  const handleFilterChange = (type: string) => {
    setFilterType(type)
  }

  /**
   * 获取筛选后的历史记录
   * @returns any[] 筛选后的记录列表
   */
  const getFilteredHistory = () => {
    if (filterType === 'all') {
      return history
    }
    return history.filter(record => record.type === filterType)
  }

  /**
   * 格式化积分数量显示
   * @param points 积分数量
   * @returns string 格式化后的积分显示
   */
  const formatPoints = (points: number) => {
    const sign = points > 0 ? '+' : ''
    return `${sign}${points}`
  }

  /**
   * 获取积分记录的颜色
   * @param points 积分数量
   * @returns string 颜色值
   */
  const getPointsColor = (points: number) => {
    return points > 0 ? '#34c759' : '#ff3b30'
  }

  // 获取筛选后的历史记录
  const filteredHistory = getFilteredHistory()

  return (
    <View className='points-history'>
      {/* 页面标题 */}
      <View className='header'>
        <Text className='title'>积分历史</Text>
      </View>

      {/* 统计信息 */}
      <View className='stats-section'>
        <View className='stats-grid'>
          <View className='stat-item'>
            <Text className='stat-value earned'>{stats.totalEarned}</Text>
            <Text className='stat-label'>累计获得</Text>
          </View>
          <View className='stat-item'>
            <Text className='stat-value used'>{stats.totalUsed}</Text>
            <Text className='stat-label'>累计使用</Text>
          </View>
          <View className='stat-item'>
            <Text className='stat-value expired'>{stats.totalExpired}</Text>
            <Text className='stat-label'>已过期</Text>
          </View>
        </View>
      </View>

      {/* 筛选器 */}
      <View className='filter-section'>
        <ScrollView className='filter-list' scrollX>
          <View 
            className={`filter-item ${filterType === 'all' ? 'active' : ''}`}
            onClick={() => handleFilterChange('all')}
          >
            <Text className='filter-text'>全部</Text>
          </View>
          <View 
            className={`filter-item ${filterType === 'order' ? 'active' : ''}`}
            onClick={() => handleFilterChange('order')}
          >
            <Text className='filter-text'>订单奖励</Text>
          </View>
          <View 
            className={`filter-item ${filterType === 'rating' ? 'active' : ''}`}
            onClick={() => handleFilterChange('rating')}
          >
            <Text className='filter-text'>评价奖励</Text>
          </View>
          <View 
            className={`filter-item ${filterType === 'share' ? 'active' : ''}`}
            onClick={() => handleFilterChange('share')}
          >
            <Text className='filter-text'>分享奖励</Text>
          </View>
          <View 
            className={`filter-item ${filterType === 'daily_login' ? 'active' : ''}`}
            onClick={() => handleFilterChange('daily_login')}
          >
            <Text className='filter-text'>每日登录</Text>
          </View>
        </ScrollView>
      </View>

      {/* 历史记录列表 */}
      <ScrollView className='history-list' scrollY>
        {loading ? (
          // 加载状态
          <View className='loading-container'>
            <Text className='loading-text'>加载中...</Text>
          </View>
        ) : filteredHistory.length === 0 ? (
          // 空状态
          <View className='empty-container'>
            <Text className='empty-icon'>💰</Text>
            <Text className='empty-text'>暂无积分记录</Text>
            <Text className='empty-desc'>快去下单获得积分吧</Text>
          </View>
        ) : (
          // 记录列表
          <View className='records-container'>
            {filteredHistory.map((record, index) => (
              <View key={index} className='record-item'>
                <View className='record-icon'>
                  <Text className='icon-text'>{getTypeIcon(record.type)}</Text>
                </View>
                
                <View className='record-info'>
                  <Text className='record-type'>{getTypeText(record.type)}</Text>
                  <Text className='record-description'>{record.description}</Text>
                  <Text className='record-time'>{formatDateTime(record.createdAt)}</Text>
                </View>
                
                <View className='record-points'>
                  <Text 
                    className='points-value'
                    style={{ color: getPointsColor(record.points) }}
                  >
                    {formatPoints(record.points)}
                  </Text>
                  {record.isExpired && (
                    <Text className='expired-tag'>已过期</Text>
                  )}
                </View>
              </View>
            ))}
          </View>
        )}
      </ScrollView>

      {/* 底部提示 */}
      <View className='footer-tip'>
        <Text className='tip-text'>积分有效期为1年，请注意及时使用</Text>
      </View>
    </View>
  )
}

// 配置页面
PointsHistory.config = {
  navigationBarTitleText: '积分明细'
} 